<script setup>

import moduleJson from "@/components/page/moduleJson"
import dataJson from "@/components/page/dataJson"
import {inject, nextTick, onMounted, reactive, ref, toRaw, toRefs, unref} from "vue";
import {CloseBold, Delete, EditPen, Plus} from "@element-plus/icons-vue";
import AgentsService from "@/service/impl/AgentsService.js";
import AgentsClassModel from "@/model/AgentsClassModel.js";
import AgentsInfoModel from "@/model/AgentsInfoModel.js";
import Dialog from "@/components/dialog/Dialog.vue";
import dialogJson from "@/components/dialog/dialogJson.js";
import FileUploadService from "@/service/impl/FileUploadService.js";


const t = inject('$t')
const message = inject('message')
const data = dataJson()
const module = moduleJson()
const agentsClassModel = ref(new AgentsClassModel())
const agentsInfoModel = ref(new AgentsInfoModel())
const pageTable = ref()
const loading = ref(false)
const classList = ref([])
const infoDialog = dialogJson()
const activeName = ref('base')
const url = window.webConfig.apiUrl()
const models = ref([])
const modelsInfo = ref([])
const knowledge = ref([])


const init = () => {
    module.value.dialog.show = false
    AgentsService.classList({}).then(res => {
        classList.value = res.data
    })
}
const editOpen = () => {
    const fun = {
        0: () => {
            module.value.dialog.title = '添加'
            agentsClassModel.value = new AgentsClassModel()
        },
        1: () => {
            module.value.dialog.title = '编辑'
            let obj = classList.value.find(item => item.id === agentsClassModel.value.id)
            agentsClassModel.value = JSON.parse(JSON.stringify(obj))
        }
    }
    agentsClassModel.value?.id ?  fun[1](init) : fun[0](init)
    module.value.dialog.show = true
    module.value.dialog.load = false
}
const editConfirm = () => {
    AgentsService.classEdit(agentsClassModel.value).then(res => {
        init();
    }).catch(e => {

    })
}
const delConfirm = () => {
    if(!agentsClassModel.value?.id){
        message.warning("请选择知识库")
        return
    }
    AgentsService.classDel(agentsClassModel.value).then(res => {
        init()
        message.success("删除成功")
        agentsClassModel.value = new AgentsClassModel()
        infoList(null)
    })
}


const infoList = (val) => {
    data.value.data.classId = val
    AgentsService.infoList(data.value.source()).then(res => {
        data.value.list = res.data
        loading.value = false
    }).catch(e => loading.value = false)
}

const delInfo = (obj) => {
    AgentsService.infoDel(obj).then(res => {
        message.success("删除成功")
        infoList(agentsClassModel.value.id)
    })
}

const onAddAgents = (item) => {
    activeName.value = 'base'
    infoDialog.value.width = '40%'
    infoDialog.value.load = true
    initConfig(() => {
        if(item){
            infoDialog.value.title = '编辑智能体'
            infoDialog.value.data = JSON.parse(JSON.stringify(item))

            return
        }
        if(!agentsClassModel.value?.id){
            message.warning("请选择分类")
            return
        }
        infoDialog.value.title = '添加智能体'
        infoDialog.value.data = new AgentsInfoModel()
        infoDialog.value.data.classId = agentsClassModel.value.id
    })
}

const initConfig = (fun) => {
    AgentsService.agentsConfig({}).then(res => {
        infoDialog.value.load = false
        infoDialog.value.show = true
        modelsInfo.value = res.data.modelConfigVOS || []
        models.value = res.data.modelClassVOS || []
        knowledge.value = res.data.knowledgeClassVOS || []
        if(fun){
            fun()
        }
    }).catch(e => {
        infoDialog.value.load = false
    })
}


const infoConfirm = () => {
    AgentsService.infoEdit(infoDialog.value.data).then(res => {
        message.success("删除成功")
        infoList(agentsClassModel.value.id)
    })
}

const onRefresh = () => {
    init()
    infoList(agentsClassModel.value.id)
}

const onChangeAvatar = () => {
    let input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = (event) => {
        let file = event.target.files[0];
        if (file) {
            FileUploadService.toLocal({
                file: file,
                path: 'avatar'
            }).then(res => {
                infoDialog.value.data.avatar = res.data
            })
        }
    };
    input.click();
}


onMounted(() => {
    module.value.layout = {
        tableLeft: false,
        width: "0px",
        table: false,
    }
    module.value.page = false
    module.value.init(null, null,
        AgentsService.url.titleDel, null, null)
    module.value.operations.width = "200px"
    module.value.dialog.width = "50%"
    init()
})

</script>
<template>
    <Page
        @refresh="onRefresh"
        :data="data"
        :module="module"
        @edit-confirm="editConfirm"
        ref="pageTable"
    >
        <template #table>
            <el-row class="card-c" v-loading="loading">
                <el-row v-for="(item,index) in data.list" style="position: relative">
                    <el-popconfirm title="确认要删除吗?" @confirm="delInfo(item)">
                        <template #reference>
                            <el-icon class="item-del"><CircleCloseFilled /></el-icon>
                        </template>
                    </el-popconfirm>
                    <el-card >
                        <template #header>
                            <el-row @click="onAddAgents(item)">
                                <el-col :span="12">
                                    <el-row class="avatar"><el-avatar shape="square"  :src="url + item.avatar" /></el-row>
                                </el-col>
                                <el-col :span="12">
                                    <el-row class="name">{{item.name}}</el-row>
                                </el-col>
                            </el-row>
                        </template>
                        <el-row class="ellipsis">
                            {{item.background}}
                        </el-row>
                    </el-card>
                </el-row>
            </el-row>
        </template>
        <template #table-left>
        </template>
        <template #operate-before>
            <el-button type="primary" :icon="agentsClassModel.id?EditPen:Plus" style="margin-left: 12px" @click="editOpen">
                {{agentsClassModel.id?'编辑':'添加'}}
            </el-button>
            <el-select v-model="agentsClassModel.id" clearable  style="width: 200px;margin:0 15px 0 15px"
                       @change="infoList">
                <el-option
                    v-for="item in classList"
                    :key="item.id"
                    :label="item.className"
                    :value="item.id"
                />
            </el-select>
            <el-popconfirm title="确认要删除吗?" @confirm="delConfirm">
                <template #reference>
                    <el-button type="danger" :icon="Delete">
                        删除
                    </el-button>
                </template>
            </el-popconfirm>
        </template>
        <template #operate-after>
            <el-button @click="onAddAgents(null)" type="primary" :icon="Plus">添加智能体</el-button>
        </template>
        <template #table-column>

        </template>
        <template #after-table-event="row">
        </template>
        <template #table-dialog>
            <el-form :rules="agentsClassModel.rules" :label-width="110" :label-position="'left'"
                     :model="agentsClassModel" style="width: 100%;padding: 5px">
                <el-form-item label="分类名称" prop="className">
                    <el-input v-model="agentsClassModel.className" autocomplete="off"/>
                </el-form-item>
            </el-form>
        </template>
        <template #table-search>

        </template>

    </Page>

    <Dialog :dialog="infoDialog" >
        <el-form :rules="infoDialog.data" :label-width="110" :label-position="'left'"
                 :model="infoDialog.data" style="width: 100%;">
            <el-tabs v-model="activeName" >
                <el-tab-pane label="智能体信息" name="base">
                    <el-form-item label="智能体头像" prop="avatar">
                        <el-avatar shape="square"  :src="url + infoDialog.data.avatar" @click="onChangeAvatar" />
                    </el-form-item>
                    <el-form-item label="智能体名称" prop="name">
                        <el-input v-model="infoDialog.data.name" autocomplete="off"/>
                    </el-form-item>
                    <el-form-item label="智能体背景" prop="background">
                        <el-input
                            v-model="infoDialog.data.background"
                            :rows="3"
                            resize="none"
                            maxlength="500"
                            type="textarea"
                        />
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="选用模型" name="models">
                    <el-form-item :label="item.className" :prop="item.filedName" v-for="item in models">
                        <el-select v-model="infoDialog.data.config.model[item.filedName]" :key="item.id">
                            <el-option
                                v-for="config in modelsInfo.filter(i => i.classType === item.classType) || []"
                                :key="config.id"
                                :label="config.name"
                                :value="config.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="选用知识库" name="knowledge">
                    <el-checkbox-group v-model="infoDialog.data.config.knowledges">
                        <el-checkbox v-for="item in knowledge" :label="item.title" :value="item.id" />
                    </el-checkbox-group>
                </el-tab-pane>
<!--                <el-tab-pane label="选用工具" name="tool">-->
<!--                    <el-form-item label="其他配置" prop="config">-->
<!--                        <el-input v-model="infoDialog.data.config" autocomplete="off"/>-->
<!--                    </el-form-item>-->
<!--                </el-tab-pane>-->
            </el-tabs>
        </el-form>
        <template #table-dialog-btn>
            <el-button @click="infoDialog.show = false">取消</el-button>
            <el-button type="primary" @click="infoConfirm">保存</el-button>
        </template>
    </Dialog>

</template>

<style lang="scss" scoped>
.card-c{
    width: 100%;height: 100%;overflow-y: auto;gap: 5px;align-content: start;
    .item-del{
        position: absolute;
        top: 0;
        right: -5px;
        z-index: 999;
        cursor: pointer;
    }
}
:deep(.el-card){
    padding: 0px !important;
    width: 200px;
}
:deep(.el-card__header){
    cursor: pointer;
    padding: 5px !important;
    > el-row{
        width: 100%;height: 50px;
    }
    .avatar{
        width: 100%;height: 50px;justify-content: start;align-content: center
    }
    .name{
        width: 100%;height: 50px;justify-content: end;align-content: center;font-size: 1em
    }
}
:deep(.el-card__body){
    padding: 5px !important;
}
.ellipsis{
    display: -webkit-box !important;
    -webkit-box-orient: vertical !important;
    -webkit-line-clamp: 3 !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    word-break: break-all; /* 强制长单词换行 */
    font-size: 14px;
    line-height: 1.5;
    height: calc(14px * 1.5 * 3);
}
</style>
